package com.yanxinim.cn.store.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.yanxinim.cn.AppConfig;
import com.yanxinim.cn.R;
import com.yanxinim.cn.store.Goods;
import com.yanxinim.cn.store.StoreGoodsAdapter;
import com.yanxinim.cn.store.StoreOrderDetailsActivity;
import com.yanxinim.cn.store.bean.OrderInfo;
import com.yanxinim.cn.util.TimeUtils;
import com.yanxinim.cn.util.ToastUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class OrderAdapter extends RecyclerView.Adapter<OrderAdapter.ViewHolder> {

    private Context context;
    private List<OrderInfo> dataList = new ArrayList<>();
    private ItemOnClickListener itemOnClickListener;
    private int selectedPosition = 0;

    public void setItemOnClickListener(ItemOnClickListener itemOnClickListener) {
        this.itemOnClickListener = itemOnClickListener;
    }

    public OrderAdapter(Context context, List<OrderInfo> dataList) {
        this.context = context;
        this.dataList = dataList;
    }


    public void cleanAll (){
        dataList.clear();
        notifyDataSetChanged();
    }
    public void addAllData(List<OrderInfo> dataListUpdate) {
        if (dataListUpdate != null && dataListUpdate.size() > 0) {
            dataList.addAll(dataListUpdate);
            notifyItemRangeChanged(dataList.size() - dataListUpdate.size(), dataListUpdate.size());
        }
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_order_list, viewGroup, false);
        return new ViewHolder(view);
    }

    @SuppressLint("DefaultLocale")
    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
        OrderInfo item = dataList.get(position);

        viewHolder.tvOrderId.setText(String.format("订单号：%s", item.getId()));

        if (item.getListOrderdata() != null) {
            StoreGoodsAdapter goodsAdapter = new StoreGoodsAdapter(context, item.getListOrderdata(),2);
            goodsAdapter.setAdapterOnClickListener((position1, data) -> itemOnClickListener.onItemClick(item, position1));
            viewHolder.rvGoodsData.setLayoutManager(new LinearLayoutManager(context));
            viewHolder.rvGoodsData.setAdapter(goodsAdapter);
            viewHolder.tvOrderGoodsNum.setText(String.format("共%d件产品", item.getListOrderdata().size()));
        }

        viewHolder.tvOrderTatal.setText(String.format("共计：￥%.2f", Double.parseDouble(item.getOrderMoney())));
        viewHolder.tvOrderTime.setText(TimeUtils.f_long_2_str(Long.parseLong(item.getOrderAtime())));
        switch (item.getOrderState()) {//0待付款，1待发货，2已发货，3已完成，4已取消，5退款中
            case "0":
                viewHolder.tvOrderStatus.setText("待付款");
                viewHolder.tvRight.setText("去支付");
                viewHolder.tvCancel.setText("取消订单");
                viewHolder.tvRight.setVisibility(View.VISIBLE);
                viewHolder.tvCancel.setVisibility(View.VISIBLE);
                break;
            case "1":
                viewHolder.tvOrderStatus.setText("待发货");
                viewHolder.tvRight.setVisibility(View.GONE);
                viewHolder.tvCancel.setVisibility(View.VISIBLE);
                viewHolder.tvCancel.setText("取消订单");
                break;
            case "2":
                viewHolder.tvOrderStatus.setText("已发货");
                viewHolder.tvRight.setText("确认收货");
                viewHolder.tvCancel.setText("取消订单");
                viewHolder.tvRight.setVisibility(View.VISIBLE);
                viewHolder.tvCancel.setVisibility(View.VISIBLE);
                break;
            case "3":
                viewHolder.tvOrderStatus.setText("已完成");
                viewHolder.tvRight.setVisibility(View.VISIBLE);
                viewHolder.tvRight.setText("删除订单");
                viewHolder.tvCancel.setVisibility(View.GONE);
                break;
            case "4":
                viewHolder.tvOrderStatus.setText("已取消");
                viewHolder.tvRight.setVisibility(View.VISIBLE);
                viewHolder.tvRight.setText("删除订单");
                viewHolder.tvCancel.setVisibility(View.GONE);
                break;
            case "5":
                viewHolder.tvOrderStatus.setText("退款中");
                viewHolder.tvRight.setVisibility(View.GONE);
                viewHolder.tvCancel.setVisibility(View.GONE);
                break;
        }

        viewHolder.itemView.setOnClickListener(v -> itemOnClickListener.onItemClick(item, position));


        viewHolder.tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateOrder("4", item.getId(),position);
            }
        });

        viewHolder.tvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (item.getOrderState()) {//0待付款，1待发货，2已发货，3已完成，4已取消，5退款中
                    case "0":
                        ToastUtil.showToast(context, "去支付");
                        break;
                    case "1":
                        break;
                    case "2":
//                        确认收货
                        updateOrder("3", item.getId(), position);
                        break;
                    case "3":
                    case "4":
                        delOrder(item.getId(), position);
                        break;
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.tv_order_id)
        TextView tvOrderId;
        @BindView(R.id.tv_order_status)
        TextView tvOrderStatus;
        @BindView(R.id.rv_goods_data)
        RecyclerView rvGoodsData;
        @BindView(R.id.tv_order_goods_num)
        TextView tvOrderGoodsNum;
        @BindView(R.id.tv_order_tatal)
        TextView tvOrderTatal;
        @BindView(R.id.tv_cancel)
        TextView tvCancel;
        @BindView(R.id.tv_right)
        TextView tvRight;
        @BindView(R.id.tv_order_time)
        TextView tvOrderTime;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }


    public interface ItemOnClickListener {
        void onItemClick(OrderInfo newType, int position);
    }

    private void delOrder(String orderId, int position) {
        Map<String, String> map = new HashMap<>();
        map.put("orderId", orderId);
        HttpUtils.get().url(AppConfig.STORE_DELETE_ORDER)
                .params(map)
                .build()
                .execute(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        JSONObject jsonObject = JSON.parseObject(result);
                        if (jsonObject.getInteger("resultCode") == 1) {
                            ((Activity)context).runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (dataList.size() ==1){
                                        dataList.clear();
                                        notifyDataSetChanged();
                                    }else {
                                        dataList.remove(position);
                                        notifyDataSetChanged();
                                    }
                                }
                            });

                        }
                    }
                });

    }

    private void updateOrder(String status, String orderId, int position) {
        Map<String, String> map = new HashMap<>();
        map.put("orderId", orderId);
        map.put("orderState", status);
        HttpUtils.get().url(AppConfig.STORE_UPDATE_ORDER)
                .params(map)
                .build()
                .execute(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        JSONObject jsonObject = JSON.parseObject(result);
                        if (jsonObject.getInteger("resultCode") == 1) {
                            ((Activity)context).runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    OrderInfo orderInfo = dataList.get(position);
                                    orderInfo.setOrderState(status);
                                    notifyItemChanged(position, orderInfo);
                                }
                            });

                        }
                    }
                });

    }
}
